package com.jlu.test.doc;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;

import java.io.IOException;

public class ESTest_Doc_Highlight {

  public static void main(String[] args) throws IOException {

//    创建es客户端
    RestHighLevelClient client = new RestHighLevelClient(
            RestClient.builder(new HttpHost("localhost",9200, "http"))
    );

//    高亮查询

    SearchRequest request = new SearchRequest();
    request.indices("user");

    SearchSourceBuilder builder = new SearchSourceBuilder();
    TermQueryBuilder query = QueryBuilders.termQuery("name", "will");

    HighlightBuilder highlightBuilder = new HighlightBuilder();
    highlightBuilder.preTags("<font color='red'>");
    highlightBuilder.postTags("</font>");
    highlightBuilder.field("name");

    builder.highlighter(highlightBuilder);


    builder.query(query);
    request.source(builder);
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);



    SearchHits hits = response.getHits();
    System.out.println(hits.getTotalHits());

    for (SearchHit hit : hits) {
      System.out.println(hit);
    }

//    关闭es客户端
    client.close();
  }
}
